package com.bbdjt.weixin.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import net.rubyeye.xmemcached.MemcachedClient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbdjt.weixin.model.Weixin;

public class WeiXinUtil {
	private static final String appid = SubsystemIp.getInstance().getValue("yjb.AppID");
	private static final String secret = SubsystemIp.getInstance().getValue("yjb.AppSecret");
	private static final String www = "http://"+SubsystemIp.getInstance().getValue("bbdjt.port");
    /*public static void main(String[] args) {
    	
    	String token = getAccess_token();
    	String jsapi_ticket = getJsapi_ticket(token);
  

        // 注意 URL 一定要动态获取，不能 hardcode
        String url = "web/wx/wx1.jsp";
        Map<String, String> ret = sign(jsapi_ticket,url);
        for (Map.Entry entry : ret.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    };*/
    
    public static String getAccess_token(MemcachedClient memcachedClient) throws Exception {
		String access_token = memcachedClient.get("weixin_access_token");
		if (null == access_token) {
			String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
			String data = HttpClientUtil.sendHttpGet(url);
			JSONObject json = JSON.parseObject(data);
			access_token = (String) json.get("access_token");
			System.out.println("获取weixin_access_token==================="+access_token);
			memcachedClient.set("weixin_access_token", 60 * 50 * 2, access_token);
		}
		return access_token;
	}
    
    public static String getJsapi_ticket(String token){
    	String url ="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi";
    	String data = HttpClientUtil.sendHttpGet(url);
    	System.out.println(data);
    	JSONObject json = JSON.parseObject(data);  
		return (String) json.get("ticket");	
    }
    
	public static Map<String, String> sign(MemcachedClient memcachedClient, String action, String doctorId) throws Exception {
		Map<String, String> sign = memcachedClient.get("weixin_jsapi_ticket_sign_" + action + doctorId);
		if (null == sign) {
			sign = WeiXinUtil.sign(getJsapi_ticket(getAccess_token(memcachedClient)), action + ".action?doctorId="+doctorId);
			memcachedClient.set("weixin_jsapi_ticket_sign_" + action + doctorId, 60 * 50 * 2, sign);
		}
		return sign;
	}
	
	public static Map<String, String> sign(MemcachedClient memcachedClient, String action, Integer doctorId) throws Exception {
		Map<String, String> sign = memcachedClient.get("weixin_jsapi_ticket_sign_" + action + doctorId);
		if (null == sign) {
			sign = WeiXinUtil.sign(getJsapi_ticket(getAccess_token(memcachedClient)), action + ".action?id="+doctorId);
			memcachedClient.set("weixin_jsapi_ticket_sign_" + action + doctorId, 60 * 50 * 2, sign);
		}
		return sign;
	}
	
    public static Map<String, String> sign(String jsapi_ticket,String action) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";
        String url = www+"/"+action;
        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                  "&noncestr=" + nonce_str +
                  "&timestamp=" + timestamp +
                  "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        System.out.println(signature);
        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
    
    
    
    public static Weixin getWeixinUser(String code) throws Exception {

		String url_shouquan_access_token = "https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid=" + SubsystemIp.getInstance().getValue("yjb.AppID") + "&secret=" + SubsystemIp.getInstance().getValue("yjb.AppSecret") + "&code=" + code
				+ "&grant_type=authorization_code";
		System.out.println("url_shouquan_access_token====================="+url_shouquan_access_token);
		String result = HttpClientUtil.sendHttpGet(url_shouquan_access_token);
		System.out.println("result====================="+result);
		Map<String, Object> map = JSON.parseObject(result);
		String access_token = (String) map.get("access_token");
		String openid = (String) map.get("openid");

		// 此处跟随第三方参数 select_appid-healthRecordId=19。select_appid参数追加形式任意

		String url_userinfo = "https://api.weixin.qq.com/sns/userinfo?" + "access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
		System.out.println("url_userinfo====================="+url_userinfo);
		map = JSON.parseObject(HttpClientUtil.sendHttpGet(url_userinfo));
		Weixin weixin = new Weixin();
		weixin.setNickname(EmojiFilter.removeNonBmpUnicode((String) map.get("nickname")));
		weixin.setHeadimaurl((String) map.get("headimgurl"));
		weixin.setOpenId(openid);
		weixin.setLanguage((String) map.get("language"));
		weixin.setSex((Integer) map.get("sex"));
		weixin.setCity((String) map.get("city"));
		weixin.setProvince((String) map.get("province"));
		weixin.setCountry((String) map.get("country"));
		
		return weixin;
	}
    
    /*public static void main(String[] args) {
    	String a = UUID.randomUUID().toString();
    	String b = Long.toString(System.currentTimeMillis() / 1000);
    	String url = "http://wx.laogay.com";
    	System.out.println(a);
    	System.out.println(b);
	}*/
}
